package ink.ykb.pdfdemo.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import org.springframework.stereotype.Component;

import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.parser.ParserEmulationProfile;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataHolder;
import com.vladsch.flexmark.util.data.MutableDataSet;

/**
 * md转html
 * 
 * @author yangkebiao
 *
 */
@Component
public class MarkDownUtil {

	public String getResourceFileContent(String resourcePath) {
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(resourcePath)));
			String s = null;
			while ((s = br.readLine()) != null) {
				result.append(System.lineSeparator() + s);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	public void writeFileContent(String resourcePath, String content) {
		FileWriter writer;
		try {
			writer = new FileWriter(resourcePath);
			writer.write(content);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String convertFile(String mdPath) {

		MutableDataHolder options = new MutableDataSet();
		options.setFrom(ParserEmulationProfile.MARKDOWN);
		options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create()));

		Parser parser = Parser.builder(options).build();
		HtmlRenderer renderer = HtmlRenderer.builder(options).build();

		String cnotent = this.getResourceFileContent(mdPath);
		Node document = parser.parse(cnotent);
		return renderer.render(document);
	}
	
	public String convertFileByHtml(String mdPath) {
		String content = this.convertFile(mdPath);
		
		String html = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\">\n" + "\n"
				+ "<link href=\"src/main/resources/doc/resource/css/github-markdown.css\" rel=\"stylesheet\">"
//				+ "<style>.markdown-body{box-sizing:border-box;min-width:200px;max-width:980px;margin:0 auto;padding:25px};</style>"
				+ "</head><body>" + "<article class=\"markdown-body\">" + content + "</article>" + "\n" + "</body></html>";
		return html;
	}

}
